package cn.jsc.user.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头的token,判断是否为null
        String token = request.getHeader("token");
        //1.1.不为null -通过token从redis获取登陆信息对象
        if(token!=null){
            Object obj = redisTemplate.opsForValue().get(token);
            if(obj!=null){
                //1.1.2.不为null放行
                //刷新token时间
                redisTemplate.opsForValue().set(token,obj,30, TimeUnit.MINUTES);
                return true;
            }
        }
        //没有登陆或登陆过期 - 跳转到登陆页面
        response.setCharacterEncoding("utf-8");
        //都是登录失败，返回一个错误 {“success”:false,"message":"noLogin"}，让前端页面
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.close();
        //1.2.为null - 没有登陆
        return false;

    }
}
